package com.oa.ylms.apps.dao.file.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.ylms.apps.constants.IDEDStates;
import com.oa.ylms.apps.dao.file.IFileCategoryDao;
import com.oa.ylms.apps.entity.file.FileCategoryValue;


public class FileCategoryDaoImpl extends HibernateDaoSupport implements IFileCategoryDao {
	
	List<FileCategoryValue> list;

	public int addFileCategory(FileCategoryValue fileCategory) throws Exception {
		if (fileCategory != null) {
			this.getHibernateTemplate().save(fileCategory);
			return fileCategory.getCategoryId();
		}
		return 0;
	}


	@SuppressWarnings("unchecked")
	public List<FileCategoryValue> queryCategoryByStates(final FileCategoryValue fileCategory) throws Exception {
		String hqlStr ="FROM FileCategoryValue fcv WHERE 1=1";
		if(fileCategory.getStates() != null){
			hqlStr += " AND fcv.states = ?";
		}
		hqlStr += " AND fcv.states <> ?";
		final String hql = hqlStr;
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				int index = -1;
				if(fileCategory.getStates() != null){
					query.setInteger(++index, fileCategory.getStates());
				}
				query.setInteger(++index, IDEDStates.DELETE);
				list = query.list();
				return list;
			}
		});
		return list;
	}

	public FileCategoryValue queryCategoryById(FileCategoryValue fileCategory)throws Exception {
		if(fileCategory!=null){
			return (FileCategoryValue) this.getHibernateTemplate().get(FileCategoryValue.class, fileCategory.getCategoryId());
		}
		return null;
	}


	public boolean editFileCategory(FileCategoryValue fileCategory) {
		if (fileCategory != null) {
			try {
				this.getHibernateTemplate().update(fileCategory);
				return true;
			} catch (Exception e) {
			}
		}
		return false;
	}


	public List<FileCategoryValue> getList() {
		return list;
	}


	public void setList(List<FileCategoryValue> list) {
		this.list = list;
	}

}
